`

need to iterate over a number of strings and run the same commands

on each one.

Here is how to create an array in bash. Save this code to a file

named array.sh and execute it.

#!/bin/bash

# Set an array

IP_ADDRESSES=(192.168.1.1 192.168.1.2 192.168.1.3)

# Print all elements in the array

echo "${IP_ADDRESSES[*]}"

# Print only the first element in the array

echo "${IP_ADDRESSES[0]}"

This script uses an array named IP_ADDRESSES that contains

three IP addresses. The first echo command prints all the elements

in the array by passing [*] to the variable name IP_ADDRESSES,

which holds the array values. The * is a representation of every array

element. Lastly, another echo command prints just the first element

in the array by specifying index zero.

Running this script should produce the following output:

$ chmod u+x arrays.sh

$ ./arrays.sh

192.168.1.1 192.168.1.2 192.168.1.3

192.168.1.1

As you can see, we were able to get bash to print all elements in

the array, as well as just the first element.

You can also delete elements from an array. The following will

delete 192.168.1.2 from the array:

IP_ADDRESSES=(192.168.1.1 192.168.1.2 192.168.1.3)

unset IP_ADDRESSES[1]

You can even swap one of the values with another value. The

following code will replace 192.168.1.1 with 192.168.1.10:

IP_ADDRESSES[0]="192.168.1.10"

You’ll find arrays particularly useful when you need to iterate

over values and perform actions against them, such as a list of IP

addresses to scan (or a list of emails to send a phishing email to).

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks